/**
  * @description: 斑马线表格
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, {Component} from 'react';
// import {Table} from '@alifd/next';
import styles from './index.module.scss';
import {getMediaById} from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';

let tableTimer;

 
@inject('chartStore') 
@observer


class TableZebra extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height: '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            columnMaps:[],
            haveData: false,
            colorColumns: [], // 特殊字段

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            pageInitFlag: true,
            affectName: '',
            requireCondition: '',
        };
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false,
                            // dataNull: true,
                            haveData: false,
                            columnMaps: {},
                            chartData: [],
                            axisArr: []
                        })
                        
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }
    
    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: true
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }

    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.setState({
                    dataNull: true
                })
            }
        } else {
            this.setState({
                dataNull: true
            })
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        });

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (storeData.affect && storeData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                storeData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (storeData.requires && storeData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                storeData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (storeData.affect &&  storeData.affect.length > 0) {
                this.setState({
                    affectName: storeData.affect[0]
                });
            }
            // 获取选择项
            if (storeData.conditionValues) {
                let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }


        // 组装当前图例的维度和度量
        let xyArr = storeData.columns ? storeData.columns.split(',') : [];
        if (storeData.data.length > 0) {
            // Object.keys(storeData.data[0]).forEach(function (key) {
            //     xyArr.push(key)
            // });
            // if (xyArr.indexOf('index') > -1) {
            //     let index = xyArr.indexOf('index');
            //     xyArr.splice(index,1);
            //     xyArr.unshift('index');
            // }
            this.setState({
                dataNull: false
            })
        }

        this.setState({
            title: storeData.title,
            chartData: storeData.data,
            axisArr: xyArr,
            columnMaps:storeData.columnMaps,
            color: storeData.colors.split(','),
            haveData: true,
            colorColumns: storeData.colorColumns
        })
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        const { saveAffectId } = this.props.chartStore;
        saveAffectId(this.state.chartId);
        this.props.onGlobalVariable(val);
    }

    // table无缝隙循环滚动
    Marquee = (table,table1,table2) => {
        if (table2.offsetTop - table.scrollTop <= 0) {
            table.scrollTop -= table1.offsetHeight;
        } else {
            table.scrollTop++;
        }
    } 
    
    



    render() {
        const _this = this;
        let Layer = this.props.layer;
        let selectVal = this.state.requireCondition[this.state.affectName] ? this.state.requireCondition[this.state.affectName] : '';
        
        const {haveData} = this.state;
        const {columnMaps} = this.state;
        const {chartData} = this.state;
        const {axisArr} = this.state;
        const {colorColumns} = this.state;
        

        // 表头
        let colnums = [];
        if (axisArr.length > 0) {
            axisArr.map((v,i) => {
                Object.keys(columnMaps).forEach(function(key){
                // for (let key in columnMaps) {
                    if (key == v && key != 'tier') {
                        colnums.push({
                            "key": v,
                            "value": columnMaps[v]
                        })
                    }
                })
            })
        }
        
        // 表数据
        let colnumsData = [];
        if (haveData && chartData.length > 0) {
            chartData.map((item,index) => {
                let objData = [];
                axisArr.map((v,i) => {
                    objData.push({
                        "key": v,
                        "value": item[v]
                    })
                })
                objData.push({
                    "key": 'tier',
                    "value": item.tier
                })
                colnumsData.push(objData);
            })
        }
        
        let maxH = 0;
        if ((colnumsData.length + 1) * 30 < this.state.height - 90) {
            maxH = (colnumsData.length + 1) * 30
        } else {
            maxH = Math.ceil((this.state.height - 90) / 30) * 30;
        }
        let lenNum = Math.ceil(maxH / 30) - 1;
        // console.log('lenNum-----',lenNum);
        // console.log('length-----',colnumsData.length);
        let tdWidth = Math.floor(100 / colnums.length) + '%';

        if (this.state.pageFlag == 'preview' && colnumsData.length > 0 && lenNum < colnumsData.length) {
            setTimeout(() => {
                tableTimer = tableTimer + this.state.id+'_'+this.state.chartId;
                if (tableTimer) window.clearInterval(tableTimer);

                let speed = 200;
                let table = document.getElementById(this.state.id+'_'+this.state.chartId+'_table');
                let table1 = document.getElementById(this.state.id+'_'+this.state.chartId+'_table1');
                let table2 = document.getElementById(this.state.id+'_'+this.state.chartId+'_table2');
                
                if (table1) {
                    table2.innerHTML = table1.innerHTML;
                    tableTimer = window.setInterval(() => {
                        this.Marquee(table,table1,table2);
                    },speed)
                }
            },2000)
        }
        
        
        console.log('colnums-------',colnums);
        console.log('colnumsData-------',colnumsData);


        return (
            
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 99,width: this.state.width,height: this.state.height,padding: '50px 3% 30px 3%'}}>
                <Layer width={this.state.width} 
                        title={this.state.title} 
                        chartId={this.state.chartId} 
                        choiceData={this.state.mainData} 
                        selectVal={selectVal}
                        onGlobalVariable={this.onGlobalVariable}
                ></Layer>
                <div style={{display: 'block',width: '100%',height: maxH,overflow: 'hidden'}}>
                    <div style={{height: '30px'}}>
                        <table className={styles.tableBox} cellpadding="0" cellspacing="0">
                            <tr>
                                {colnums.map((item,index) => {
                                    return (
                                        <th style={{width: tdWidth,backgroundColor: item.value.indexOf('接受者') > -1 ? 'rgba(255,141,73,0.15)' : 'rgba(36,206,255,0.15)',color: item.value.indexOf('接受者') > -1 ? '#FF8D49' : this.state.color[0]}}> {item.value} </th>
                                    )
                                })}
                            </tr>
                        </table>
                    </div>
                    <div id={this.state.id+'_'+this.state.chartId+"_table"} style={{overflow: 'hidden',height: maxH-30+ 'px'}}>
                        <div id={this.state.id+'_'+this.state.chartId+"_table1"}>
                            <table className={styles.tableBox} cellpadding="0" cellspacing="0">
                                {colnumsData.length > 0 && colnumsData.map((item,index) => {
                                    let color = this.state.color[1] || '#72f1f8';
                                    item.map((v,i) => {
                                        if (v.key == 'tier') {
                                            color = parseInt(v.value) == 1 ? '#c00000' : parseInt(v.value) == 2 ? '#ff0000' : parseInt(v.value) == 3 ? '#ffa500' : parseInt(v.value) == 4 ? '#ffff00' : parseInt(v.value) == 5 ? '#52C72E' : item.tier == 6 ? '#0FA33D' : '#72f1f8'
                                        }
                                    })
                                    return (
                                        <tr>
                                            {item.map((v,i) => {
                                                if (v.key != 'tier') {
                                                    let defaultColor = '#72f1f8';
                                                    if (colorColumns && colorColumns.length > 0 && colorColumns.indexOf(v.key) > -1) {
                                                        defaultColor = color;
                                                    }
                                                    return (
                                                        <td style={{padding: 0,margin: 0,width: tdWidth + 'px !important',color: defaultColor}}> {v.value} </td>
                                                    )
                                                }
                                            })}
                                        </tr>
                                    )
                                })}
                            </table>
                        </div>
                        <div id={this.state.id+'_'+this.state.chartId+"_table2"}></div>
                    </div>
                </div>
                { this.state.dataNull && <p style={{height: '100px',lineHeight: '100px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>}
            </div>
        );
    }


}

export default TableZebra;

